package zuo.algo.c19;

import zuo.algo.util.SortUtils;

import java.util.Random;

/**
 * 01:11-可以预先将一些数据处理好放到Map或数组中
 * 牛牛有一些排成一行的正方形。每个正方形已经被染成红色或者绿色。牛牛现在可
 * 以选择任意一个正方形然后用这两种颜色的任意一种进行染色,这个正方形的颜色将
 * 会被覆盖。牛牛的目标是在完成染色之后,每个红色R都比每个绿色6距离最左侧近。
 * 牛牛想知道他最少需要涂染几个正方形。
 *
 * 如样例所示:s=RGRGR
 *
 * 我们涂染之后变成RRRGG满足要求了,涂染的个数为2,没有比这个更好的涂染方案。
 */
public class A04 {

    public static int exc1(String str) {
        char[] chars = str.toCharArray();
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < chars.length; i++) {
            int count = 0;
            for (int j = 0; j < i; j++) {
                if (chars[j] != 'R') {
                    count++;
                }
            }
            for (int j = i; j < chars.length; j++) {
                if (chars[j] != 'G') {
                    count++;
                }
            }
            res = Math.min(count, res);
        }
        return res;
    }

    public static int exc2(String str) {
        char[] chars = str.toCharArray();
        int[] left = new int[chars.length];
        int[] right = new int[chars.length];
        int count = 0;
        for (int i = 0; i < chars.length; i++) {
            left[i] = count;
            if (chars[i] == 'G') {
                count++;
            }
        }
        count = 0;
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] == 'R') {
                count++;
            }
            right[i] = count;
        }
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < chars.length; i++) {
            count = left[i] + right[i];
            res = Math.min(count, res);
        }
        return res;
    }

    public static void main(String[] args) {
        Random random = new Random();
        char[] chars = new char[] {'R', 'G'};
        for (int i = 0; i < 1000000; i++) {
            int len = random.nextInt(1000) + 1;
            char[] res = new char[len];
            for (int j = 0; j < len; j++) {
                int idx = random.nextInt(2);
                res[j] = chars[idx];
            }
            String str = new String(res);
            int res1 = exc1(str);
            int res2 = exc2(str);
            System.out.println("res1=" + res1 + " res2=" + res2 + " - " + str);
            if (res1 != res2) {
                System.out.println("error");
                break;
            }
        }
    }
}
